<?php
define ( "DS" ,  DIRECTORY_SEPARATOR );
define ( "BASE_PATH" ,  dirname(__FILE__).DS.'..' );

class PAutoLoader{
    private static $classPath = array();
    private static $path = __DIR__;

    
    public static function register(){
        spl_autoload_register(__CLASS__ . '::autoLoader');
    }
    public static function autoLoader($class)
    {
        //echo 'class==' . $class . "\n";
        if(isset(self::$classPath[$class])) {
            require self::$classPath[$class];
            return;
        }
        $baseClasspath = \str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';
        $libs = array(
            __DIR__ ,
            __DIR__ . '/../handler',
            __DIR__ . '/../gen-php'
        );
        foreach ($libs as $lib) {
            $classpath = $lib . DIRECTORY_SEPARATOR . $baseClasspath;
            //echo 'classpath==' . $classpath . "\n";
            if (is_file($classpath)) {
                //echo 'is_file==' . $classpath . "\n";
                self::$classPath[$class] = $classpath;
                require "{$classpath}";
                return;
            }
        }
        // 加载thrift接口类
        self::loadThriftService($class);

    }
    private static function loadThriftService($class){
        //echo 'class==' . $class . "\n";
        $libs = array(
            //__DIR__ ,
            __DIR__ . '/../handler',
            __DIR__ . '/../gen-php'
        );
        
        $m = explode('\\', $class);
        
        if(count($m) <= 1)
        {
            return;
        }
        
        $class = array_pop($m);
        $namespace = implode('\\', $m);
        foreach ($libs as $ns => $dir)
        {
            if(
                0 === preg_match('#(.+)(if|client|processor|rest)$#i', $class, $n) &&
                0 === preg_match('#(.+)_[a-z0-9]+_(args|result)$#i', $class, $n)
            )
            {
                $className = 'Types';
            }
            else
            {
                $className = $n[1];
            }
            $file = $dir.DIRECTORY_SEPARATOR .
            str_replace('\\', DIRECTORY_SEPARATOR, $namespace) .
            DIRECTORY_SEPARATOR .
            $className . '.php';
            //echo 'file==' . $file . "\n";
            if (file_exists($file) == true)
            {
                //echo 'file_exists==' . $file . "\n";
                self::$classPath[$class] = $file;
                require $file;
                return;
            }
        }
    }
}

PAutoLoader::register();
// PAutoLoader::autoLoader("Swoole\Service\ThriftServiceClient");
// print_r(get_declared_classes());
